﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Configuration;
using System.Diagnostics;

namespace WowRaidListTracker.DAL
{
    public class CRUDReader
    {
        private static CRUDReader crud;
        public static CRUDReader Crud
        {
            get
            {
                if (crud != null)
                    return crud;
                else
                {
                    crud = Initialize();
                    return crud;
                }
            }
        }

        private XmlDocument qud;
        private string qudFile;

        public CRUDReader(string filePath)
        {
            qud.Load(filePath);
        }

        public CRUDReader()
        {
            try
            {
                qudFile = ConfigurationManager.AppSettings.Get("QudFile");
                qud = new XmlDocument();
                qud.Load(qudFile);
            }
            catch (TypeInitializationException tie)
            {
                Trace.WriteLine("Type initialization error caught. {0}", tie.Message);
            }
            catch (NullReferenceException nre)
            {
                Trace.WriteLine("Null reference. {0}", nre.Message);
            }
        }

        internal static CRUDReader Initialize()
        {
            CRUDReader c = new CRUDReader();
            return c;
        }

        public string get(string name, QUDType type)
        {
            string result = string.Empty;
            switch (type)
            {
                case QUDType.Select:
                    result = Select(name);
                    break;
                case QUDType.Insert:
                    result = Insert(name);
                    break;
                case QUDType.Update:
                    result = Update(name);
                    break;
                case QUDType.Delete:
                    result = Delete(name);
                    break;
            }
            return result;
        }

        private string Delete(string name)
        {
            return qud.SelectSingleNode("/StoredQueries/Deletes/Delete[@name='" + name + "']/sql").InnerText;
        }

        private string Update(string name)
        {
            return qud.SelectSingleNode("/StoredQueries/Updates/Update[@name='" + name + "']/sql").InnerText;
        }

        private string Select(string name)
        {
            return qud.SelectSingleNode("/StoredQueries/Selects/Select[@name='" + name + "']/sql").InnerText;
        }

        private string Insert(string name)
        {
            return qud.SelectSingleNode("/StoredQueries/Inserts/Insert[@name='" + name + "']/sql").InnerText;
        }

        public enum QUDType
        {
            Select,
            Insert,
            Update,
            Delete
        }
    }
}
